import React, { Component } from 'react';
import '../styles/Login.css'
// 导入登录请求封装
import { user_login } from '../api/login.js'
class Login extends Component {
    constructor(props) {
        super(props);
        this.state = { phone: '', pass: '', agree: false }
    }

    //更改表单变为授控组件
    handleChange(e) {
        this.setState({
            [e.target.name]: e.target.type == 'checkbox' ? e.target.checked : e.target.value
        })
    }

    //    登录时触发
    Login() {
          //   先进行判断手机号是否符合正则
          if (/^1[3456789]\d{9}$/.test(this.state.phone)) {
              // 手机号合适后即可发送请求
              user_login({ phone: this.state.phone, pass: this.state.pass }).then((res) => {
                  console.log(res);
                  if (res.data.code == 400) {
                      alert("该账号已被注册")
                  }
                  else if (res.data.code == 200) {
                    localStorage.setItem("token",res.data.token)
                      alert("登录成功")
                  }
              })
          } else {
              alert('手机号有误')
  
          }

    }

    render() {
        return (
            <div className='login'>
                <div className='title'>登录页</div>
                <div className='block'>
                    <input type="text" name='phone' value={this.state.phone} onChange={(e) => { this.handleChange(e) }} placeholder='请输入手机号' />
                </div>
                <div className='block'>
                    <input type="text" name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} placeholder='请输入密码' />
                </div>
                <div className='check'>
                    <input type="checkbox" name='agree' checked={this.state.agree} onChange={(e) => { this.handleChange(e) }} />同意用户协议
                </div>
                <div className='block'>
                    <input type="button" value='登录' onClick={() => { this.Login() }} />
                </div>
            </div>
        );
    }
}

export default Login;